# -*- coding: utf-8 -*-
from . import BaseController
from backend.libs import myjson as json
from backend.models import Distributor, DistributorSettlement, DistributorOrder
from datetime import datetime
from backend.libs import err_result_const as err_const
from django.db import connections
from decimal import Decimal


class List(BaseController):

    def get(self):
        d = Distributor.objects
        mobile = self.get_argument('mobile', '')
        if mobile:
            d = d.filter(mobile=mobile)
        state = self.int_argument('state', -1)
        if state > -1:
            d = d.filter(state=state)
        d = d.order_by('state', '-created_at')
        number_per_page = self.int_argument('pageSize', 100)
        paginator = self.pagination_contain_objects_no_records(d.all(), number_per_page=number_per_page)
        paginator['records'] = Distributor.objects.build_data(paginator['objects'])
        del paginator['objects']
        return self.render_json(data=paginator)


class Detail(BaseController):

    def get(self):
        id = self.int_argument('id', -1)
        if id <= 0:
            return self.render_json(code=1001, msg='参数错误')
        d = Distributor.objects.filter(id=id).first()
        if not d:
            return self.render_json(code=1001, msg='分销商不存在')
        return self.render_json(data=d.to_dict())


class Create(BaseController):

    def post(self):
        data = json.loads(self.request.body)
        user_id = int(data.get('user_id', 0))
        if user_id <= 0:
            return self.render_json(code=err_const.PARAM_ERR['code'], msg=err_const.PARAM_ERR['msg'])
        mobile = data.get('mobile', '')
        id_card = data.get('id_card', '')
        shroff_account_num = data.get('shroff_account_num', '')
        receiptor = data.get('receiptor', '')
        bank_of_deposit = data.get('bank_of_deposit', '')
        if not mobile or not id_card or not shroff_account_num or not receiptor or not bank_of_deposit:
            return self.render_json(code=err_const.PARAM_ERR['code'], msg=err_const.PARAM_ERR['msg'])
        state = int(data.get('state', 0))
        disabled = int(data.get('disabled', 0))
        Distributor.objects.create(user_id=user_id, mobile=mobile, id_card=id_card, shroff_account_num=shroff_account_num, 
                        receiptor=receiptor, bank_of_deposit=bank_of_deposit, state=state, disabled=disabled)
        return self.render_json(msg='新建分销商成功')


class Update(BaseController):

    def post(self):
        data = json.loads(self.request.body)
        id = int(data.get('id', 0))
        if id <= 0:
            return self.render_json(code=err_const.PARAM_ERR['code'], msg=err_const.PARAM_ERR['msg'])
        d = Distributor.objects.filter(id=id).first()
        mobile = data.get('mobile', '')
        if mobile:
            d.mobile = mobile
        id_card = data.get('id_card', '')
        if id_card:
            d.id_card = id_card
        shroff_account_num = data.get('shroff_account_num', '')
        if shroff_account_num:
            d.shroff_account_num = shroff_account_num
        receiptor = data.get('receiptor', '')
        if receiptor:
            d.receiptor = receiptor
        bank_of_deposit = data.get('bank_of_deposit', '')
        if bank_of_deposit:
            d.bank_of_deposit = bank_of_deposit
        state = int(data.get('state', -1))
        if state > -1:
            d.state = state
        disabled = int(data.get('disabled', -1))
        if disabled > -1:
            d.disabled = disabled
        d.save()
        
        return self.render_json(msg='分销商信息更新成功')


class Delete(BaseController):

    def post(self, distributor_id):
        distributor_id = int(distributor_id)
        if distributor_id <= 0:
            return self.render_json(code=err_const.PARAM_ERR['code'], msg=err_const.PARAM_ERR['msg'])
        tag = Distributor.objects.filter(id=distributor_id).first()
        if tag:
            tag.delete()

        return self.render_json(msg='删除分销商信息成功')


class SettlementList(BaseController):

    def get(self):
        d = DistributorSettlement.objects
        settlement_id = self.get_argument('settlement_id', '')
        if settlement_id:
            d = d.filter(settlement_id=settlement_id)
        distributor_id = self.get_argument('distributor_id', '')
        if distributor_id:
            d = d.filter(distributor_id=distributor_id)
        d = d.order_by('state', '-created_at').select_related('distributor')
        number_per_page = self.int_argument('pageSize', 100)
        paginator = self.pagination_contain_objects_no_records(d.all(), number_per_page=number_per_page)
        paginator['records'] = DistributorSettlement.objects.build_data(paginator['objects'])
        del paginator['objects']
        return self.render_json(data=paginator)


class UpdateSettlement(BaseController):

    def post(self):
        data = json.loads(self.request.body)
        id = int(data.get('id', 0))
        state = int(data.get('state', -1))
        if id <= 0 or state <= 0:
            return self.render_json(code=err_const.PARAM_ERR['code'], msg=err_const.PARAM_ERR['msg'])
        d = DistributorSettlement.objects.filter(id=id).first()
        d.state = state
        d.settle_at = datetime.now()
        d.save()

        distributor_order_list = DistributorOrder.objects.filter(settlement_id=d.settlement_id).all()
        for do in distributor_order_list:
            do.entered_account = do.entered_account + do.settle_account
            do.settle_account = Decimal('0.00')
            do.state = DistributorOrder.ENTERED
            do.save()
        
        return self.render_json(msg='分销商分成结算状态更新成功')


class QueryDistributorUsers(BaseController):

    def get(self):
        nickname = self.get_argument('nickname', '')
        data = {'records': []}
        if not nickname:
            return self.render_json(data=data)
        sql = '''
            SELECT u.id AS user_id, u.nickname, d.id AS distributor_id FROM users u LEFT JOIN `distributors` d ON u.id=d.user_id WHERE u.nickname LIKE '%s';
            '''
        param = '%s%s' % (nickname, '%')
        sql = sql % param
        with connections['default'].cursor() as cursor:
            cursor.execute(sql)
            data_in_db = cursor.fetchall()
            for d in data_in_db:
                if not d[2]:
                    continue
                tmp_dict = {'distributor_id': d[2], 'value': d[1]}
                data['records'].append(tmp_dict)
        return self.render_json(data=data)


